#include "deamon.h"
#include "server.h"

void * threadDeamon (void *th) {
	deamon *thz = (deamon *)th;
	while(1) {
	pthread_mutex_lock(&Server::mutex);
	std::map<QString,wells> toIterate = Server::wMap;
	pthread_mutex_unlock(&Server::mutex);
	std::map<QString,wells>::iterator begin = toIterate.begin();
		printf("TIMER %i\n",toIterate.size());
		for(;begin != toIterate.end(); begin++) {
			pthread_mutex_lock(&Server::mutex);
			std::map<QString,wells>::iterator i = Server::wMap.find(begin->second.name);
			if(i != Server::wMap.end()){
				i->second.timeLeft--;
				if(i->second.timeLeft == 0)
					i->second.timeLeft = i->second.timeDefaut;
			}
			pthread_mutex_unlock(&Server::mutex);
			begin->second.timeLeft--;
			if(begin->second.timeLeft == 0) {
				wells tmp = begin->second; 
				begin->second.timeLeft = begin->second.timeDefaut;
				printf("POCO NOME %i EXPIROU %i\n",tmp.id,tmp.idSimulador);
				QStringList DataFromWell = thz->mainSocket->trestGetLetterFromWellAux(tmp.id,tmp.idSimulador);
				std::cout << "ERRO NA AQUISICAO DA CARTA3\n";
				DataFromWell += thz->mainSocket->alarmToDB(tmp.id,tmp.idSimulador);
				thz->mainSocket->dbConnection.saveLetterInDB(tmp.id,tmp.idSimulador,DataFromWell);
			}
		}
		sleep(60);
	}
}


deamon::deamon() {
	mainSocket = new SocketClient();
	if(!mainSocket->dbConnection.connectToDb("grupo01","grupo01","Grupo01")) {
		printf("Erro ao conectar com o banco\n");
		exit(0);
	}
	mainSocket->treatMastersList();
	mainSocket->dbConnection.getWellList();
}

void deamon::start(int t) {
	this->timeout = t;
	//pthread_create(&thread,NULL,threadDeamon,(void *)this);
}
